import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/monitor',
    name: 'Monitor',
    component: () => import('../views/Monitor.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/alarm',
    name: 'Alarm',
    component: () => import('../views/Alarm.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/history',
    name: 'History',
    component: () => import('../views/History.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('../views/Settings.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'mine',
        name: 'MineManagement',
        component: () => import('../views/settings/MineManagement.vue')
      },
      {
        path: 'site',
        name: 'SiteManagement',
        component: () => import('../views/settings/SiteManagement.vue')
      },
      {
        path: 'device',
        name: 'DeviceManagement',
        component: () => import('../views/settings/DeviceManagement.vue')
      },
      {
        path: 'alarm',
        name: 'AlarmManagement',
        component: () => import('../views/settings/AlarmManagement.vue')
      },
      {
        path: 'user',
        name: 'UserManagement',
        component: () => import('../views/settings/UserManagement.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  
  if (to.meta.requiresAuth && !isLoggedIn) {
    // 需要登录但未登录，重定向到登录页
    next('/login')
  } else if (to.path === '/login' && isLoggedIn) {
    // 已登录但访问登录页，重定向到首页
    next('/')
  } else {
    next()
  }
})

export default router 